<?php
/**
 * Created by PhpStorm.
 * User: Raytine
 * Date: 2020/1/14
 * Time: 1:39
 */

namespace App\Service;


use App\Exceptions\ApiException;
use App\User;
use GuzzleHttp\Client;

class MiniWorkService
{
    protected $corp_id;
    protected $secret;
    protected  $agent_id;
    protected $app_id;
    public function __construct()
    {
        $this->corp_id=config('wechat.work.default.corp_id');
        $this->secret=config('wechat.work.default.secret');
        $this->agent_id=config('wechat.work.default.agent_id');
        $this->app_id=config('wechat.mini_program.default.app_id');
    }
    public function jscode2session($code){
      $client=  new Client();
      $response= $client->get('https://qyapi.weixin.qq.com/cgi-bin/miniprogram/jscode2session',[
          'query'=>[
              'access_token'=>$this->access_token(),
              'js_code'=>$code,
              'grant_type'=>'authorization_code'
          ]
      ]);
       return  $result= json_decode($response->getBody()->getContents(),true);
    }
    public function access_token(){


     return \Cache::remember('access_token',6000,function(){
          $client=  new Client();
          $response= $client->get('https://qyapi.weixin.qq.com/cgi-bin/gettoken',[
              'query'=>[
                  'corpid'=>$this->corp_id,
                  'corpsecret'=>$this->secret
              ]
          ]);
          $result= json_decode($response->getBody()->getContents(),true);
          if ($result['errcode']==0){
              return $result['access_token'];
          }
          throw new ApiException('access_token错误');
      });
    }
    public function send(User $user,$title,$url='pages/index/index',$content_item=[]){
        $client=  new Client();
        \Log::channel('mini')->info($user->name);
        if (config('app.env')=='local')    {
            $user=User::find(650);
        }
        $response= $client->post('https://qyapi.weixin.qq.com/cgi-bin/message/send',[
            'query'=>[
                'access_token'=>$this->access_token(),
            ],
            'body'=>json_encode([
                'touser'=>$user->userid,
                'msgtype'=>'miniprogram_notice',
                'miniprogram_notice'=>[
                    "appid"=> $this->app_id,
                    "page"=>$url,
                    "title"=>$title,
                    "description"=> date("Y-m-d H:i:s",time()),
                    'content_item'=>$content_item
                ],

            ],JSON_UNESCAPED_UNICODE)
        ]);

        $result=json_decode($response->getBody()->getContents(),true);

        if ($result['errcode']!=0){
            \Log::channel('mini')->error($title.$user->name,$result);
        }else{
            \Log::channel('mini')->info($title.$user->name,$result);
        }

        return $result;
    }
}
